<?php

namespace App\Admin\Service\Traits;

use App\Common\Exception\ApiMessageException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 开关
 *
 * Trait SwitchServiceTrait
 */
trait SwitchServiceTrait
{
    /**
     * 开关切换数值更新
     *
     * @param array $data
     *
     * @return void
     * @throws ApiMessageException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function toggle(array $data): void
    {
        $id          = $data[$this->model->getPrimaryKey()];
        $this->model = $this->model->find($id);
        if (!$this->model) {
            throw new ApiMessageException('数据不存在，无法修改');
        }

        $this->model->setAttrs($data);

        $this->model->save();
    }
}